package com.example.book.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.example.book.service.OssService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Data
public class OssServiceImpl implements OssService {
    @Value("${oss.file.endpoint}")
    private  String endpoint;

    @Value("${oss.file.keyId}")
    private  String accessKeyId;

    @Value("${oss.file.keySecret}")
    private  String accessKeySecret;

    @Value("${oss.file.bucketName}")
    private  String bucketName;

    @Value("${oss.file.fileHost}")
    private  String fileName;


    /**
     * 上传图片进oss的方法
     * @param file  文件
     * @param path  路径
     * @return   访问的url名称
     */
//    https://liuxingphoto.oss-cn-shenzhen.aliyuncs.com/2022-12-06/3112e1a6-a7d2-4b86-afac-9d207c8a298f.png
    public String uploadOss(@RequestPart MultipartFile file){
        //首先构建ossclient客户端
        System.out.println(file.toString());
        System.out.println(endpoint.toString());
        System.out.println(accessKeyId.toString());
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //生成文件路径方法
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date()) + "/";
        String objectName = format + UUID.randomUUID() + ".png";

        try{
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,objectName,new ByteArrayInputStream(file.getBytes()));
            ossClient.putObject(putObjectRequest);
        }catch (Exception e){
          e.printStackTrace();
          return null;
        }finally {
            ossClient.shutdown();
        }

        return fileName+objectName;
    }

    @Override
    public boolean delete(String relativePath) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            oss.deleteObject(bucketName,relativePath);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            oss.shutdown();
        }
        return true;

    }

}
